package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.enumeration.OperationType;
import com.sky.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect {


    //切入点表达式
    @Pointcut("execution(* com.sky.mapper.*.*(..))&& @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut() {
    }



    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {//lian jie dian shi bei kong zhi de fang fa

        //1 获取方法签名并获取注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType type = autoFill.value();

        //2 获取方法参数
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        Object entry = args[0];

        //3. 获取数据
        LocalDateTime now = LocalDateTime.now();
        Long id = CurrentHolder.getCurrentId();

        //4.赋值
        if (type == OperationType.INSERT) {
            Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
            Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);

            //通过映射来赋值
            setUpdateTime.invoke(entry, now);
            setUpdateUser.invoke(entry, id);
            setCreateTime.invoke(entry, now);
            setCreateUser.invoke(entry, id);
        }
        if (type == OperationType.UPDATE) {
        }
        Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
        Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);

        setUpdateTime.invoke(entry, now);
        setUpdateUser.invoke(entry, id);
    }


}
